package cn.edu.ncut.cs.springboot.petmanagementsystem.controller;

import cn.edu.ncut.cs.springboot.petmanagementsystem.common.PageResult;
import cn.edu.ncut.cs.springboot.petmanagementsystem.common.Result;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.ServiceReservation;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.PetServiceService;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.UserService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/foster")
@Tag(name = "宠物寄养服务模块")
public class FosterController {

    @Autowired
    private PetServiceService petServiceService;

    @Autowired
    private UserService userService;

    @Operation(summary = "用户提交宠物寄养预约申请")
    @PostMapping("/reserve")
    public Result<?> reserveFoster(@RequestBody FosterReservationRequest request) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            // 使用ServiceReservation实体，服务类型为寄养（假设服务类型ID为特定值）
            ServiceReservation reservation = new ServiceReservation();
            reservation.setUserId(user.getId());
            reservation.setPetId(request.getPetId());
            reservation.setServiceTypeId(request.getServiceTypeId()); // 寄养服务类型ID
            reservation.setReservationDate(request.getReservationDate());
            reservation.setReservationTime(request.getReservationTime());
            reservation.setEmployeeId(request.getEmployeeId());
            reservation.setSpecialRequirements(request.getSpecialRequirements());
            reservation.setTotalAmount(request.getTotalAmount());

            boolean success = petServiceService.reserveService(reservation);
            return success ? Result.success("预约成功") : Result.error("预约失败");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("提交寄养预约失败", e);
            return Result.error("预约失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取寄养服务信息")
    @GetMapping("/info")
    public Result<?> getFosterInfo() {
        try {
            Map<String, Object> info = petServiceService.getFosterServiceInfo();
            return Result.success(info);
        } catch (Exception e) {
            log.error("获取寄养服务信息失败", e);
            return Result.error("获取失败: " + e.getMessage());
        }
    }

    @Operation(summary = "查询用户提交的寄养预约记录")
    @GetMapping({"/records", "/my-records"})
    public PageResult<cn.edu.ncut.cs.springboot.petmanagementsystem.vo.FosterRecordVO> getFosterList(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "宠物ID") @RequestParam(required = false) Long petId) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return PageResult.pageError("用户不存在");
            }

            IPage<cn.edu.ncut.cs.springboot.petmanagementsystem.vo.FosterRecordVO> page = petServiceService.getFosterRecordList(user.getId(), petId, pageNum, pageSize);
            return PageResult.success(page);
        } catch (Exception e) {
            log.error("查询寄养预约记录失败", e);
            return PageResult.pageError("查询失败: " + e.getMessage());
        }
    }

    @Operation(summary = "管理员确认并安排寄养服务")
    @PutMapping("/confirm/{id}")
    public Result<?> confirmFoster(
            @Parameter(description = "预约ID") @PathVariable Long id) {
        try {
            boolean success = petServiceService.confirmReservation(id);
            return success ? Result.success("确认成功") : Result.error("确认失败");
        } catch (Exception e) {
            log.error("确认寄养服务失败", e);
            return Result.error("确认失败: " + e.getMessage());
        }
    }

    @Operation(summary = "标记寄养服务已完成")
    @PutMapping("/finish/{id}")
    public Result<?> finishFoster(
            @Parameter(description = "预约ID") @PathVariable Long id) {
        try {
            boolean success = petServiceService.finishReservation(id);
            return success ? Result.success("标记成功") : Result.error("标记失败");
        } catch (Exception e) {
            log.error("标记寄养服务完成失败", e);
            return Result.error("标记失败: " + e.getMessage());
        }
    }

    @Operation(summary = "用户取消未开始的寄养预约")
    @DeleteMapping("/cancel/{id}")
    public Result<?> cancelFoster(
            @Parameter(description = "预约ID") @PathVariable Long id) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            boolean success = petServiceService.cancelReservation(id, user.getId());
            return success ? Result.success("取消成功") : Result.error("取消失败");
        } catch (Exception e) {
            log.error("取消寄养预约失败", e);
            return Result.error("取消失败: " + e.getMessage());
        }
    }

    @Operation(summary = "计算寄养费用")
    @GetMapping("/calculate-cost")
    public Result<?> calculateCost(
            @Parameter(description = "开始日期时间") @RequestParam String startDate,
            @Parameter(description = "结束日期时间") @RequestParam String endDate,
            @Parameter(description = "宠物ID") @RequestParam(required = false) Long petId) {
        try {
            LocalDateTime start = LocalDateTime.parse(startDate);
            LocalDateTime end = LocalDateTime.parse(endDate);
            
            Map<String, Object> cost = petServiceService.calculateFosterCost(start, end, petId);
            return Result.success(cost);
        } catch (Exception e) {
            log.error("计算寄养费用失败", e);
            return Result.error("计算失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取寄养房间信息")
    @GetMapping("/rooms")
    public Result<?> getRooms() {
        try {
            List<Map<String, Object>> rooms = petServiceService.getFosterRooms();
            return Result.success(rooms);
        } catch (Exception e) {
            log.error("获取寄养房间信息失败", e);
            return Result.error("获取失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取寄养日志")
    @GetMapping("/logs/{fosterId}")
    public Result<?> getFosterLogs(
            @Parameter(description = "寄养记录ID") @PathVariable Long fosterId) {
        try {
            List<Map<String, Object>> logs = petServiceService.getFosterLogs(fosterId);
            return Result.success(logs);
        } catch (Exception e) {
            log.error("获取寄养日志失败", e);
            return Result.error("获取失败: " + e.getMessage());
        }
    }

    @Data
    public static class FosterReservationRequest {
        private Long petId;
        private Long serviceTypeId;
        private LocalDate reservationDate;
        private LocalTime reservationTime;
        private Long employeeId;
        private String specialRequirements;
        private java.math.BigDecimal totalAmount;
    }
}
